<template>
	<view>
		<view class="img-upload">
			<view class="img-item" v-for="(image,index) in imgList" :key='index'>
				<u-image :src="image" width='200rpx' height='200rpx' @tap='previewImage(index)' mode="aspectFill"></u-image>
				<view class="close-icon" @tap.stop='handleDelete(index)'>
					<u-icon name="plus" class="icon"></u-icon>
				</view>
			</view>
			<view class="up-block" @tap="chooseImage" v-if="imgList.length<max">
				<u-icon class="plus-icon" name="plus"></u-icon>
				<view class="plus-desc">添加图片</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props:{
			max:{
				type:Number,
				default:3
			}
		},
		data() {
			return {
				imgList: []
			}
		},
		methods: {
			/*
			 * @previewImage 预览图片
			 * @handleDelete 删除图片
			 * @chooseImage  选择上传图片
			 */
			previewImage(index) {
				const _this = this
				uni.previewImage({
					current: index,
					urls: _this.imgList,
					indicator: 'default',
					loop: true
				})
			},
			handleDelete(index) {
				const _this = this
				uni.showModal({
					title: '提示',
					content: '是否删除这张图片',
					success(res) {
						if (res.confirm) {
							_this.imgList.splice(index, 1)
							_this.$emit('change',_this.imgList)
						}
					}
				});
			},
			chooseImage() {
				const _this = this
				uni.chooseImage({
					sizeType: ['compressed','original'],
					sourceType: ['album', 'camera'],
					success(filePath) {
						console.log(filePath)
						_this.imgList = _this.imgList.concat(filePath.tempFilePaths)
						_this.$emit('change',_this.imgList)
					},
					fail(e) {
						console.log(e)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.img-upload {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;

		.img-item {
			overflow: hidden;
			margin: 0 24rpx 10rpx 0;
			position: relative;

			&:nth-child(3n) {
				margin-right: 0;
			}

			.close-icon {
				width: 100rpx;
				height: 100rpx;
				transform: rotate(45deg);
				position: absolute;
				right: -48rpx;
				top: -48rpx;
				background-color: rgba($color: #000000, $alpha: .5);

				.icon {
					color: #F29100;
					font-size: 40rpx;
					margin: 60rpx 32rpx;
				}
			}
		}

		.up-block {
			width: 200rpx;
			height: 200rpx;
			border-radius: 10rpx;
			background-color: #f5f5f5;
			text-align: center;

			&:active {
				opacity: .6;
			}

			.plus-icon {
				margin-top: 25%;
				color: #666;
				font-size: 36rpx;
			}

			.plus-desc {
				color: #666;
				margin-top: 10rpx;
			}
		}
	}
</style>
